/**
 * 数据中台接口服务
 */

interface DataCenterConfig {
  baseUrl: string
  key: string
  secret: string
}

interface TokenResponse {
  code: number
  message: string
  description: string
  result: {
    access_token: string
    expires_in: string
  }
}

interface StudentData {
  XH: string // 学号
  XM: string // 姓名
  XB: string // 性别
  BYXX: string // 毕业学校
  KL: string // 科类
  TDCJ: string // 投档成绩
  YW: string // 语文
  SX: string // 数学
  WY: string // 外语
  ZH: string // 综合
  ZF: string // 总分
  LQNJ: string // 录取年级
  YXMC: string // 院系名称
  ZYMC: string // 专业名称
  BJMC: string // 班级名称
  HKSZDQ: string // 户口所在地区
  LQTZSZY: string // 录取通知书专业
  CSNY: string // 出生年月
  SF: string // 省份
}

// 竞赛获奖信息数据类型
interface CompetitionAwardData {
  XM: string // 学生姓名
  XH: string // 学号
  SJDL: string // 实践大类
  SJMK: string // 实践模块
  HDMC: string // 活动或奖项名称
  REWARD_XF: string // 得分分值
  CREATED_AT: string // 得分时间
  COMMENT: string // 备注
  TEAM_ID: string // 团队编号
  REWARD_NAME: string // 奖励等级
  EVENT_NAME: string // 竞赛名称
  NF: string // 年份
  CERTIFICATE_DATE: string | null // 获奖日期
  JSDJ: string // 竞赛等级
}

// 学院数据类型
interface CollegeData {
  DWDM: string // 单位代码
  DWMC: string // 单位名称
  DWJC: string // 单位简称
  LSDWH: string // 隶属单位号
  DWYXBS: string // 单位有效标识
}

// 专业数据类型
interface MajorData {
  ZYDM: string // 专业代码
  ZYDMC: string // 专业名称
  ZYJC: string // 专业简称
  ZYYWMC: string // 专业英文名称
  DWH: string // 单位号
  XZ: string // 学制
  QYBZ: string // 启用标志
  DWMC: string // 单位名称
}

interface StudentsResponse {
  code: number
  message: string
  description: string
  uuid: string
  result: {
    page: number
    per: number
    total: number
    max_page: number
    data_struct: Record<string, string>
    data: StudentData[]
    encrypted_field: string
  }
}

// 竞赛获奖信息响应类型
interface CompetitionAwardsResponse {
  code: number
  message: string
  description: string
  result: {
    page: number
    per: number
    total: number
    max_page: number
    data_struct: Record<string, string>
    data: CompetitionAwardData[]
    encrypted_field: string
  }
}

// 学院响应类型
interface CollegesResponse {
  code: number
  message: string
  description: string
  result: {
    page: number
    per: number
    total: number
    max_page: number
    data_struct: Record<string, string>
    data: CollegeData[]
    encrypted_field: string
  }
}

// 专业响应类型
interface MajorsResponse {
  code: number
  message: string
  description: string
  result: {
    page: number
    per: number
    total: number
    max_page: number
    data_struct: Record<string, string>
    data: MajorData[]
    encrypted_field: string
  }
}

class DataCenterService {
  private config: DataCenterConfig
  private accessToken: string | null = null
  private tokenExpiresAt: number | null = null

  constructor() {
    this.config = {
      baseUrl: process.env.DATA_CENTER_BASE_URL || 'https://dct.zufe.edu.cn',
      key: process.env.DATA_CENTER_KEY || '20250626495419381425045998223367960',
      secret: process.env.DATA_CENTER_SECRET || '74c946ec7b5d98dd305775b4872ff6dfd2e0f387'
    }
  }

  /**
   * 获取访问令牌
   */
  async getAccessToken(): Promise<string> {
    // 检查token是否还有效
    if (this.accessToken && this.tokenExpiresAt && Date.now() < this.tokenExpiresAt) {
      return this.accessToken
    }

    const url = `${this.config.baseUrl}/open_api/authentication/get_access_token`
    const params = new URLSearchParams({
      key: this.config.key,
      secret: this.config.secret
    })

    try {
      const response = await fetch(`${url}?${params}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      console.log('1111',`${url}?${params}`);
      
      const data: TokenResponse = await response.json()
      console.log(222);
      
      if (data.code !== 10000) {
        throw new Error(`API error: ${data.message}`)
      }

      this.accessToken = data.result.access_token
      console.log(this.accessToken,'this.accessToken');
      
      // 设置过期时间（提前5分钟过期）
      this.tokenExpiresAt = Date.now() + (parseInt(data.result.expires_in) - 300) * 1000

      return this.accessToken
    } catch (error) {
      console.error('获取访问令牌失败:', error)
      throw new Error('获取访问令牌失败')
    }
  }

  /**
   * 获取学生数据
   */
  async getStudents(page: number = 1, perPage: number = 10, filters?: Partial<StudentData>): Promise<StudentsResponse['result']> {
    const token = await this.getAccessToken()

    const url = `${this.config.baseUrl}/open_api/customization/tgxxsbzksryxx/full`

    const requestBody = {
      page: page.toString(),
      per_page: perPage.toString(),
      access_token: token,
      ...filters
    }

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data: StudentsResponse = await response.json()

      if (data.code !== 10000) {
        // 如果是查询结果为空，返回空数据而不是抛出错误
        if (data.message === '查询结果为空') {
          return {
            page: page,
            per: perPage,
            total: 0,
            max_page: 0,
            data_struct: {},
            data: [],
            encrypted_field: ''
          }
        }
        throw new Error(`API error: ${data.message}`)
      }

      return data.result
    } catch (error) {
      console.error('获取学生数据失败:', error)
      throw new Error('获取学生数据失败')
    }
  }

  /**
   * 获取所有学生数据（分页获取）
   */
  async getAllStudents(filters?: Partial<StudentData>): Promise<StudentData[]> {
    const allStudents: StudentData[] = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const result = await this.getStudents(currentPage, 100, filters)
      allStudents.push(...result.data)
      
      hasMore = currentPage < result.max_page
      currentPage++
      
      // 添加延迟避免请求过快
      if (hasMore) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    return allStudents
  }

  /**
   * 转换数据中台学生数据为本地格式
   */
  transformStudentData(dcStudent: StudentData) {
    return {
      studentNumber: dcStudent.XH,
      name: dcStudent.XM,
      gender: dcStudent.XB,
      graduateSchool: dcStudent.BYXX,
      subjectCategory: dcStudent.KL,
      admissionScore: dcStudent.TDCJ,
      chineseScore: dcStudent.YW,
      mathScore: dcStudent.SX,
      englishScore: dcStudent.WY,
      comprehensiveScore: dcStudent.ZH,
      totalScore: dcStudent.ZF,
      admissionGrade: dcStudent.LQNJ,
      departmentCode: dcStudent.YXMC,
      majorCode: dcStudent.ZYMC,
      className: dcStudent.BJMC,
      householdRegion: dcStudent.HKSZDQ,
      admissionMajor: dcStudent.LQTZSZY,
      birthDate: dcStudent.CSNY ? new Date(dcStudent.CSNY) : null,
      province: dcStudent.SF,
      syncStatus: 'pending' as const
    }
  }

  /**
   * 获取学生竞赛获奖信息
   */
  async getCompetitionAwards(page: number = 1, perPage: number = 10, filters?: Partial<CompetitionAwardData>): Promise<CompetitionAwardsResponse['result']> {
    const token = await this.getAccessToken()

    const url = `${this.config.baseUrl}/open_api/customization/tgxjxbksjshjxx/full`

    const requestBody = {
      page: page.toString(),
      per_page: perPage.toString(),
      ...filters
    }

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      const data: CompetitionAwardsResponse = await response.json()

      if (data.code !== 10000) {
        // 如果是查询结果为空，返回空数据而不是抛出错误
        if (data.message === '查询结果为空') {
          return {
            page: page,
            per: perPage,
            total: 0,
            max_page: 0,
            data_struct: {},
            data: [],
            encrypted_field: ''
          }
        }
        throw new Error(`API error: ${data.message}`)
      }

      return data.result
    } catch (error) {
      console.error('获取竞赛获奖数据失败:', error)
      throw new Error('获取竞赛获奖数据失败')
    }
  }

  /**
   * 获取学院数据
   */
  async getColleges(page: number = 1, perPage: number = 10, filters?: Partial<CollegeData>): Promise<CollegesResponse['result']> {
    const token = await this.getAccessToken()

    const url = `${this.config.baseUrl}/open_api/customization/tgxxxyxsdwxx/full`

    const requestBody = {
      page: page.toString(),
      per_page: perPage.toString(),
      access_token: token,
      ...filters
    }

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data: CollegesResponse = await response.json()

      if (data.code !== 10000) {
        // 如果是查询结果为空，返回空数据而不是抛出错误
        if (data.message === '查询结果为空') {
          return {
            page: page,
            per: perPage,
            total: 0,
            max_page: 0,
            data_struct: {},
            data: [],
            encrypted_field: ''
          }
        }
        throw new Error(`API error: ${data.message}`)
      }

      return data.result
    } catch (error) {
      console.error('获取学院数据失败:', error)
      throw new Error('获取学院数据失败')
    }
  }

  /**
   * 获取专业数据
   */
  async getMajors(page: number = 1, perPage: number = 10, filters?: Partial<MajorData>): Promise<MajorsResponse['result']> {
    const token = await this.getAccessToken()

    const url = `${this.config.baseUrl}/open_api/customization/tgxjxbzkszyxx/full`

    const requestBody = {
      page: page.toString(),
      per_page: perPage.toString(),
      access_token: token,
      ...filters
    }

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data: MajorsResponse = await response.json()

      if (data.code !== 10000) {
        // 如果是查询结果为空，返回空数据而不是抛出错误
        if (data.message === '查询结果为空') {
          return {
            page: page,
            per: perPage,
            total: 0,
            max_page: 0,
            data_struct: {},
            data: [],
            encrypted_field: ''
          }
        }
        throw new Error(`API error: ${data.message}`)
      }

      return data.result
    } catch (error) {
      console.error('获取专业数据失败:', error)
      throw new Error('获取专业数据失败')
    }
  }

  /**
   * 获取所有学院数据（分页获取）
   */
  async getAllColleges(filters?: Partial<CollegeData>): Promise<CollegeData[]> {
    const allColleges: CollegeData[] = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const result = await this.getColleges(currentPage, 100, filters)
      allColleges.push(...result.data)

      hasMore = currentPage < result.max_page
      currentPage++

      // 添加延迟避免请求过快
      if (hasMore) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    return allColleges
  }

  /**
   * 获取所有专业数据（分页获取）
   */
  async getAllMajors(filters?: Partial<MajorData>): Promise<MajorData[]> {
    const allMajors: MajorData[] = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const result = await this.getMajors(currentPage, 100, filters)
      allMajors.push(...result.data)

      hasMore = currentPage < result.max_page
      currentPage++

      // 添加延迟避免请求过快
      if (hasMore) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    return allMajors
  }
}

export const dataCenterService = new DataCenterService()
export type {
  StudentData,
  StudentsResponse,
  CompetitionAwardData,
  CompetitionAwardsResponse,
  CollegeData,
  CollegesResponse,
  MajorData,
  MajorsResponse
}
